package com.rockcent.wechat.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.Mall;
import com.rockcent.mall.lib.domain.MerchantOrder;
import com.rockcent.mall.lib.dto.CustomerDto;
import com.rockcent.mall.lib.dto.MerchantOrderDto;
import com.rockcent.mall.lib.helper.MallOrderLogisticsHelper;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MerchantOrderRepository;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.CustomerHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Marco on 16-11-11.
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class LogisticsController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(LogisticsController.class);

    @Autowired
    private CustomerHelper customerHelper;

    @Autowired
    private MallOrderLogisticsHelper mallOrderLogisticsHelper;

    @Autowired
    private MerchantOrderRepository merchantOrderRepository;

    @Autowired
    MallRepository mallRepository;

    /**
     * @api {get} /api/v2/order/logistics/query 快递100实时快递查询接口
     * @apiGroup logistics
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id merchantOrderId
     * @apiParam {String} logisticsCode 快递编码
     * @apiParam {String} logisticsNumber 快递编号
     *
     * @apiSuccess {String} message 消息体，请忽略
     * @apiSuccess {String} state 快递单当前签收状态，包括0在途中、1已揽收、2疑难、3已签收、4退签、5同城派送中、6退回、7转单等7个状态，其中4-7需要另外开通才有效
     * @apiSuccess {String} status 通讯状态，请忽略
     * @apiSuccess {String} condition 快递单明细状态标记，暂未实现，请忽略
     * @apiSuccess {String} ischeck 是否签收标记，请忽略，明细状态请参考state字段
     * @apiSuccess {String} com 快递公司编码,一律用小写字母
     * @apiSuccess {String} nu 单号
     * @apiSuccess {String} data 最新查询结果，全量，倒序（即时间最新的在最前）
     * @apiSuccess {Long} data_context 内容
     * @apiSuccess {String} data_time 时间，原始格式
     * @apiSuccess {String} data_ftime 格式化后时间
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "message": "ok",
     *      "state": "0",
     *      "status": "200",
     *      "condition": "F00",
     *      "ischeck": "0",
     *      "com": "yuantong",
     *      "nu": "V030344422",
     *      "data" :[{
     *          "context" : "上海分拨中心/装件入车扫描",
     *          "time" : "2012-08-28 16:33:19",
     *          "ftime" : "2012-08-28 16:33:19"
     *      },
     *      ........
     *      ]
     *  }
     * }
     */
    @RequestMapping(value = Routes.ORDER_LOGISTICS_QUERY, method = RequestMethod.GET)
    public JsonResult query(HttpServletRequest request, MerchantOrderDto dto){
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if(dto.getId()==null){
                jsonResult.remind("id 不能为空",log);
                return;
            }
            if(StringUtils.isBlank(dto.getLogisticsCode())){
                jsonResult.remind("快递公司编码 不能为空",log);
                return;
            }
            if(StringUtils.isBlank(dto.getLogisticsNumber())){
                jsonResult.remind("快递单号 不能为空",log);
                return;
            }
            Mall mall = mallRepository.findOne(customerDto.getMallId());
            if(mall==null) {
                jsonResult.remind("mall id 不能为空",log);
                return;
            }
            if(mall.getIsLogisticsAccess()==null || mall.getIsLogisticsAccess().equals(Whether.NO)) {
                jsonResult.remind("没有开通访问权限",log);
                return;
            }
            MerchantOrder merchantOrder = merchantOrderRepository.findOne(dto.getId());
            if (merchantOrder == null) {
                jsonResult.remind("订单 记录不存在",log);
                return;
            }
            String result = mallOrderLogisticsHelper.getLogisticsResponse(dto.getLogisticsCode(),dto.getLogisticsNumber());
            jsonResult.data=result;
            log.info("======================>kuaidi100 C interface response : {}", result);
            if(!StringUtils.isBlank(result)) {
                Map<String, Object> map = null;
                try {
                    map = mallOrderLogisticsHelper.parseJSON2Map(result);
                } catch (Exception e) {
                    log.info("======================>kuaidi100 C error message : {}", e.getMessage());
                }
                if(map!=null && map.size()>0 && map.get("state")!=null) {
                    Map<String, Object> params = new HashMap<String,Object>();
                    params.put("orderNum",merchantOrder.getOrderNum());
                    params.put("marketOrderNum",merchantOrder.getMarketOrderNum());
                    params.put("remark",result);
                    params.put("sourceType","C");
                    params.put("status",map.get("state"));
                    params.put("merchantId",customerDto.getId());
                    params.put("logisticsCode",dto.getLogisticsCode());
                    params.put("logisticsNumber",dto.getLogisticsNumber());

                    //更新订单物流信息与订单状态
                    mallOrderLogisticsHelper.updateOrderLogisticsAndMarketOrder(params);
                }
            }
        };
        return doing.go(request, log);

    }
}
